﻿# 加载System.Drawing.Common库
Add-Type -AssemblyName System.Drawing

function Compress-Image {
    param (
        [Parameter(Mandatory=$true)]
        [string]$ImagePath,  # 图片文件的完整路径
        
        [Parameter(Mandatory=$true)]
        [int]$Quality       # 压缩后的图片质量（1-100）
    )

    if ($Quality -lt 1 -or $Quality -gt 100) {
        throw "Quality must be between 1 and 100."
    }

    try {
        # 打开原始图片
        $image = [System.Drawing.Image]::FromFile($ImagePath)

        # 设置编码参数以调整质量
        $encoderParams = New-Object System.Drawing.Imaging.EncoderParameters(1)
        $encoderParams.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter([System.Drawing.Imaging.Encoder]::Quality, $Quality)

        # 获取JPEG编码器
        $jpegEncoder = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object {$_.MimeType -eq 'image/jpeg'}

        # 构建输出文件名
        $outputPath = [System.IO.Path]::ChangeExtension($ImagePath, "_compressed.jpg")

        # 保存压缩后的图片到新的文件
        $image.Save($outputPath, $jpegEncoder, $encoderParams)

        # 关闭原始图片对象
        $image.Dispose()

        Write-Output "Compressed image saved to: $outputPath"
    } catch {
        Write-Error "An error occurred while compressing the image: $_"
    }
}

# 示例调用
Compress-Image -ImagePath "D:\Path\To\Your\Image.jpg" -Quality 80